package com.aiprompt;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

@SpringBootTest
@Component
public class BigModelAPi {
    @Value("${api.key}")
    private String API_KEY = "";
    @Value("${api.url}")
    private String API_URL = "";

    //    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    @Test
    void sendApi() {

        if (API_KEY.equals("")) {
            System.out.println("API_KEY有问题");
            return;
        }

        String response = callDeepSeekApi();
        System.out.println("API响应: " + response);

        // 使用Hutool解析响应
        cn.hutool.json.JSONObject jsonResponse = JSONUtil.parseObj(response);
        String content = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getStr("content");
        System.out.println("AI回复: " + content);
    }

    public String callDeepSeekApi() {
        // 创建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "glm-4.5");
        requestBody.put("stream", false);

        // 创建消息数组
        JSONArray messages = new JSONArray();

        // 系统消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个提示词生成助手，现在用户要学习react，他是一个小白，请你生成优质的提示词帮助用户");
        messages.add(systemMessage);

        // 用户消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "Hello!");
        messages.add(userMessage);

        requestBody.put("messages", messages);

        // 发送请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + API_KEY)
                .body(requestBody.toString())
                .timeout(30000) // 30秒超时
                .execute();

        // 检查响应状态
        if (response.getStatus() != 200) {
            throw new RuntimeException("API请求失败: HTTP " + response.getStatus());
        }

        return response.body();
    }
}
